package com.zoe.thread.th02_企业写法;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author Zoe
 * @Date: 2021/04/30
 * @Description 卖30张票demo
 */
class Ticket02 {
    private int number = 30;

    private Lock lock = new ReentrantLock();

    public void saleTicket() {
        lock.lock();
        try {
            // 操作资源类方法
            if (number > 0) {

                System.out.println(Thread.currentThread().getName() + "  卖出第：" + number-- + " 张票；还剩下：" + number);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
};

public class SaleTicketLock {
    public static void main(String[] args) {
        Ticket02 ticket02 = new Ticket02();

        // 匿名内部类方法
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 调用操作资源类方法
                for (int i = 0; i < 40; i++) {
                    ticket02.saleTicket();
                    try {
                        TimeUnit.MILLISECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "售票员1").start();

        // lambda表达式
        new Thread(() -> {
            // 调用操作资源类方法
            for (int i = 0; i < 40; i++) {
                ticket02.saleTicket();

                try {
                    TimeUnit.MILLISECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "售票员2").start();

    }
}
